Getting Started With Python

In this notebook we will see the basic data types available in Python and how to use them

Writing our first Python program

Open the terminal and run python to start the python shell. (Bonus points for using ipython)


In [1]:
print 'hello, world!'


hello, world!

Printing a string is that simple :)

Let's try few more things.


In [2]:
2 + 2


Out[2]:
4

In [3]:
5/2


Out[3]:
2

In [6]:
5/2.0


Out[6]:
2.5

In [7]:
print "hello " + " world"


hello  world

Available Datatypes in Python

  • Integers
  • Floats
  • Strings
  • Complex numbers
  • Boolean

See examples below

Variables in Python

  • Python is dynamically typed. (Also called duck typing).
  • The types of the variables are decided based on the values assigned to them. Let's see how.

We create a variable fruit and print its data type. type is a built in python function which gives us the type of an object


In [23]:
fruit = 'apple'
print type(fruit)


<type 'str'>

Now we will assign a numeric value to the variable fruit and see its type


In [22]:
fruit = 10
print 'Fruit is now of type: ' + str(type(fruit))


Fruit is now of type: <type 'int'>

Let's try assigning it a float value.


In [10]:
fruit = 10.0
print type(fruit)


<type 'float'>

Python also has built in support for complex numbers


In [24]:
complex_number1 = 10 + 2j
print type(complex_number1)


<type 'complex'>

In [19]:
is_true = True
print is_true
print type(is_true)


True
<type 'bool'>

Exponentiation operator in Python


In [25]:
2 ** 10


Out[25]:
1024

String concatenation in Python

+ operator is used to join together two strings in Python


In [30]:
first_name = 'John'
last_name = 'Doe'
print first_name + ' ' + last_name


John Doe

Exercise

Try basic mathematical operations (+, -, *, /) with these data types and see how they work.

  • What happens if you multiply a string with a number?
  • What happens if you divide two integers?
  • What happens if you try to multiply two really large numbers?

In [ ]: